using System.Security.Cryptography;
using System.IO;
using System.Text;
using Furion.Authorization;
using Furion.DataEncryption.Extensions;

namespace SB2.Core;

public class JwtHandler : AppAuthorizeHandler
{
    /// <summary>
    /// 重写 Handler 添加自动刷新
    /// </summary>
    /// <param name="context"></param>
    /// <returns></returns>
    public override async Task HandleAsync(AuthorizationHandlerContext context)
    {
        // 自动刷新Token
        if (JWTEncryption.AutoRefreshToken(context, context.GetCurrentHttpContext(),
            App.GetOptions<JWTSettingsOptions>().ExpiredTime,
            App.GetOptions<RefreshTokenSettingOptions>().ExpiredTime))
        {
            await AuthorizeHandleAsync(context);
        }
        else
        {
            context.Fail(); // 授权失败
            DefaultHttpContext currentHttpContext = context.GetCurrentHttpContext();
            if (currentHttpContext == null)
                return;
            currentHttpContext.SignoutToSwagger();
        }
    }

    /// <summary>
    /// 授权判断逻辑，授权通过返回 true，否则返回 false
    /// </summary>
    /// <param name="context"></param>
    /// <param name="httpContext"></param>
    /// <returns></returns>
    public override async Task<bool> PipelineAsync(AuthorizationHandlerContext context, DefaultHttpContext httpContext)
    {
        // 此处已经自动验证 Jwt Token的有效性了，无需手动验证
        return check(httpContext) && await CheckAuthorzieAsync(httpContext);
    }


    /// <summary>
    /// 检查加密信息，防止伪造请求
    /// </summary>
    /// <param name="httpContext"></param>
    /// <returns></returns>
    bool check(DefaultHttpContext httpContext)
    {
        var requestEncrypt = App.Configuration["RequestEncrypt"]; // 请求是否加密
        if (!string.IsNullOrEmpty(requestEncrypt))
        {
            // 获取摘要
            if (!httpContext.Request.Headers.ContainsKey("Abstract"))
                return false;
            var abstractstr = httpContext.Request.Headers["Abstract"];
            // 摘要 对比
            switch (httpContext.Request.Method)
            {
                case "POST":
                case "PUT":
                    return CheckPost(httpContext, requestEncrypt, abstractstr);
                case "GET":
                    return CheckGET(httpContext, requestEncrypt, abstractstr);
                default:
                    return false;
            }
        }
        return true;
    }

    bool CheckPost(DefaultHttpContext httpContext, string requestEncrypt, string abstractstr)
    {
        var RequestBody = new StreamReader(httpContext.Request.BodyReader.AsStream()).ReadToEnd();//读取body
        byte[] content1 = Encoding.UTF8.GetBytes(RequestBody);//替换字符串并且字符串转换成字节
        var requestBodyStream = new MemoryStream();//创建一个流 
        requestBodyStream.Seek(0, SeekOrigin.Begin);//设置从0开始读取
        requestBodyStream.Write(content1, 0, content1.Length);//把修改写入流中
        httpContext.Request.Body = requestBodyStream;//把修改后的内容赋值给请求body
        httpContext.Request.Body.Seek(0, SeekOrigin.Begin);
        // Console.WriteLine(RequestBody);
        // Console.WriteLine(httpContext.Request.ContentType);
        if (httpContext.Request.ContentType.Contains("form-data") && RequestBody.Contains("Content-Type: image"))
        {
            // 文件 如何验证？？？
            return false;
        }
        else
        {
            return (requestEncrypt + RequestBody + requestEncrypt).ToMD5Compare(abstractstr);
        }

    }
    bool CheckGET(DefaultHttpContext httpContext, string requestEncrypt, string abstractstr)
    {
        var RequestBody = (httpContext.Request.Path + "").Replace("/", "").Replace("-", "");
        // Console.WriteLine(requestEncrypt + RequestBody + requestEncrypt);
        // Console.WriteLine((requestEncrypt + RequestBody + requestEncrypt).ToMD5Encrypt());
        // Console.WriteLine(abstractstr);
        return (requestEncrypt + RequestBody + requestEncrypt).ToMD5Compare(abstractstr);
    }

    /// <summary>
    /// 检查权限
    /// </summary>
    /// <param name="httpContext"></param>
    /// <returns></returns>
    private static async Task<bool> CheckAuthorzieAsync(DefaultHttpContext httpContext)
    {
        // 管理员跳过判断
        if (App.User.FindFirst(ClaimConst.CLAINM_SUPERADMIN)?.Value == ((int)AdminType.SuperAdmin).ToString()) return true;
        // 路由名称
        var routeName = httpContext.Request.Path.Value[1..].Replace("/", ":");

        // 不需要验证的路由
        // var defalutRoute = new List<string>()
        // {
        // };

        // if (defalutRoute.Contains(routeName)) return true;

        // 获取用户权限集合（按钮或API接口）
        var allPermissionList = PermissionCode.GetApis();
        var currUserId = Convert.ToInt64(App.User.FindFirst(ClaimConst.CLAINM_USERID)?.Value);
        var permissionList = new List<string>();
        //await App.GetService<ISysMenuService>().GetLoginPermissionList(currUserId);

        // 检查授权
        // 菜单中没有配置按钮权限，则不限制
        return allPermissionList.All(u => u != routeName) || permissionList.Contains(routeName);
    }
}

